<template>
    <view class="">
        <wd-search v-model="searchValue" @search="handlesearch" hide-cancel placeholder-left placeholder="请输入关键字">
            <template #prefix>
                <wd-popover mode="menu" :content="menu" @menuclick="handleSearchChange">
                    <view class="search-type">
                        <text>{{ searchType }}</text>
                        <wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
                    </view>
                </wd-popover>
            </template>
        </wd-search>
        <wd-message-box />
        <wd-toast />
        <wd-tabs v-model="activeTab" auto-line-width @change="handleTabChange">
            <wd-tab v-for="tab in tabs" :key="tab.value" :title="tab.label" :name="tab.value">
                <view class="px-1 py-1">
                    <wd-table :data="list[tab.value]" :height="600" :border="false" @row-click="handleClick">
                        <wd-table-col v-for="(col, index) in columns[tab.value]" :key="index" :prop="col.prop"
                            :label="col.label" :width="col.width || '100'" :align="col.align || 'center'">
                            <template #value="{ row }">
                                <template v-if="col.prop.includes('.')">
                                    <!-- 如果是嵌套属性，拆分路径并按路径访问数据 -->
                                    {{ getNestedValue(row, col.prop) || '-' }}
                                </template>
                                <template v-else-if="col.isTag">
                                    <wd-tag custom-class="space"
                                        :type="col.color ? col.color(row[col.prop]) : 'primary'">
                                        {{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
                                    </wd-tag>
                                </template>
                                <template v-else>
                                    {{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
                                </template>
                            </template>
                        </wd-table-col>
                        <wd-table-col prop="grade" label="操作" width="180" fixed align="center">
                            <template #value="{ row }">
                                <!-- <text class="px-1 text-#4d80f0" @click.stop="handleProcessDetail(row)">
                                    查看
                                </text> -->
                                <template v-if="activeTab === 'overview'">
                                    <text class="px-1 text-#4d80f0" @click.stop=" handleDetail(row.id, true)">
                                        详情
                                    </text>
                                    <text class="px-1 text-#4d80f0" @click.stop=" handleAddOrEdit(row.id, true)">
                                        修改
                                    </text>
                                    <text class="px-1 text-#4d80f0" @click.stop="handleDelete(row.id)">
                                        删除
                                    </text>
                                    <text class="px-1 text-#4d80f0" @click.stop="handleExpedite(row)">
                                        催办
                                    </text>
                                </template>
                                <template v-if="activeTab === 'detail'">
                                    <text class="px-1 text-#4d80f0" @click.stop="handleReply(row)">
                                        回复
                                    </text>
                                </template>
                            </template>
                        </wd-table-col>
                    </wd-table>
                </view>
            </wd-tab>
        </wd-tabs>
        <Pagination :total="total" :pageNo="queryParams.pageNo" :pageSize="queryParams.pageSize"
            @update:pageNo="changePage" />
        <view class="mx-12 my-8 ">
            <up-button text="新增" color="#5ac725" shape="circle" @click="handleAddOrEdit()"></up-button>
        </view>
        <wd-popup v-model="detailPopupVisible" position="center" custom-style="width:80%; height:60%" lock-scroll>

            <wd-form ref="detailForm" labelWidth="120" :model="detailData">
                <wd-cell-group border>
                    <wd-card type="rectangle">
                        <template #title>
                            <view class="" style="display: flex;">
                                <span style="display: flex;align-items: center;margin-left: 10px;">详情</span>
                            </view>
                        </template>
                        <view class="">


                            <wd-input v-model="detailData.supName" type="textarea" label="督办名称" placeholder="请输入督办名称"
                                prop="content" readonly />
                            <wd-input v-model="detailData.userId" type="textarea" label="督办名称" placeholder="请输入督办名称"
                                prop="content" readonly />
                            <wd-input v-model="detailData.userName" label="执行人" prop="content" readonly />

                            <!-- <wd-select-picker v-model="detailData.userId" label="执行人" :columns="userList" clearable
                                filterable value-key="id" label-key="nickname" :show-confirm="false" prop="userId" /> -->
                            <wd-input v-model="detailData.content" type="textarea" label="督办内容" placeholder="请输入督办内容"
                                prop="content" readonly />
                            <wd-datetime-picker type="datetime" label="开始日期" prop="beginTime"
                                v-model="detailData.beginTime" readonly />
                            <wd-datetime-picker type="datetime" label="预计结束日期" prop="endTime"
                                v-model="detailData.endTime" readonly />
                            <wd-datetime-picker type="datetime" label="完成时间" prop="realEndTime"
                                v-if="detailData.realEndTime" v-model="detailData.realEndTime" readonly />
                            <wd-cell title="附件" title-width="80px" prop="url">

                                <text class="file-link" @click="previewFile(detailData.url)">
                                    {{ getFileName(detailData.url, { isUrl: true, maxLength: 15 }) || '无' }}
                                </text>
                            </wd-cell>
                        </view>
                        <template #footer>
                            <view class="flex justify-evenly mx-4 my-2">

                                <wd-button type="error" @click="detailPopupVisible = false" custom-class="custom-shadow"
                                    block>取消</wd-button>

                            </view>
                        </template>
                    </wd-card>
                </wd-cell-group>
            </wd-form>

        </wd-popup>
        <wd-popup v-model="expeditePopupVisible" position="center" custom-style="width:80%; height:40%" lock-scroll>

            <wd-form ref="auditForm" labelWidth="120" :model="expediteForm" :rules="expediteRules">
                <wd-cell-group border>
                    <wd-card type="rectangle">
                        <template #title>
                            <view class="" style="display: flex;">
                                <span style="display: flex;align-items: center;margin-left: 10px;">催办内容</span>
                            </view>
                        </template>
                        <view class="">


                            <wd-input v-model="expediteForm.content" type="textarea" label="催办内容" placeholder="请输入催办内容"
                                prop="content" />
                            <wd-cell title="附件" title-width="100px" prop="url">
                                <wd-upload v-model:file-list="fileList" :action="globalConfig.uploadUrl" limit="1"
                                    accept="all" :header="headerObj"
                                    @success="(response: any) => handleUploadSuccess(item, response, 'expedite')" />
                            </wd-cell>
                        </view>
                        <template #footer>
                            <view class="flex justify-evenly mx-4 my-2">

                                <wd-button type="error" @click="expeditePopupVisible = false"
                                    custom-class="custom-shadow" block>取消</wd-button>
                                <wd-button type="success" @click="submitExpedite" custom-class="w-8"
                                    block>提交</wd-button>
                            </view>
                        </template>
                    </wd-card>
                </wd-cell-group>
            </wd-form>

        </wd-popup>
        <wd-popup v-model="replyPopupVisible" position="center" custom-style="width:80%; height:40%" lock-scroll>

            <wd-form ref="replyFormRef" labelWidth="120" :model="replyForm" :rules="replyRules">
                <wd-cell-group border>
                    <wd-card type="rectangle">
                        <template #title>
                            <view class="" style="display: flex;">
                                <span style="display: flex;align-items: center;margin-left: 10px;">回复内容</span>
                            </view>
                        </template>
                        <view class="">


                            <wd-input v-model="replyForm.replyContent" type="textarea" label="回复内容"
                                placeholder="请输入回复内容" prop="content" />
                            <wd-cell title="附件" title-width="100px" prop="url">
                                <wd-upload v-model:file-list="replyFileList" :action="globalConfig.uploadUrl" limit="1"
                                    accept="all" :header="headerObj"
                                    @success="(response: any) => handleUploadSuccess(item, response, 'reply')" />
                            </wd-cell>
                        </view>
                        <template #footer>
                            <view class="flex justify-evenly mx-4 my-2">

                                <wd-button type="error" @click="replyPopupVisible = false" custom-class="custom-shadow"
                                    block>取消</wd-button>
                                <wd-button type="success" @click="submitReply" custom-class="w-8" block>提交</wd-button>
                            </view>
                        </template>
                    </wd-card>
                </wd-cell-group>
            </wd-form>

        </wd-popup>
    </view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { ref, onMounted, nextTick } from 'vue'
import { DICT_TYPE, getIntDictOptions, getDictLabel, getDictColor } from '@/utils/dict'
import { getNestedValue } from '@/utils/fileUtils'
import { useMessage, useToast } from 'wot-design-uni'
import { SupervisionVO, SupervisionApi } from '@/api/oa/supervision'
import { getSimpleUserList } from '@/api/system/user'
import { getAccessToken } from '@/utils/auth'
import { getFileName, parseArrayField, previewFile, buildFileList } from '@/utils/fileUtils'
import * as TaskApi from '@/api/bpm/task'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { formatPast2, formatDate } from '@/utils/formatTime'
import { expediting } from '@/utils/processinstance'
import { login } from '@/api/login'


const globalConfig = (getApp() as any).globalData.config;
const headerObj = ref({ Authorization: 'Bearer ' + getAccessToken() })

const message = useMessage()
const toast = useToast()

/**
 * 催办相关数据
 */
const detailPopupVisible = ref(false) // 详情弹窗控制
const detailData = ref<any>({});
/**
 * 催办相关数据
 */
// 催办弹窗控制
const expeditePopupVisible = ref(false)

const fileList = ref<any[]>([]);
const detailFileList = ref<any[]>([]);
const auditForm = ref<any>(null);
// 催办表单数据
const expediteForm = ref<any>({
    content: '',
    url: '',
    supId: ''
})
// 催办表单校验规则
const expediteRules = {
    content: [
        { required: true, message: '请输入催办内容', trigger: 'blur' }
    ]
}
/**
 * 回复相关数据
 */
// 回复弹窗控制
const replyPopupVisible = ref(false)
const replyFileList = ref<any[]>([]);
const replyFormRef = ref<any>(null);
// 回复表单数据
const replyForm = ref<any>({
    replyContent: '',
    replyAttachment: '',
    id: ''
})
// 回复表单校验规则
const replyRules = {
    replyContent: [
        { required: true, message: '请输入回复内容', trigger: 'blur' }
    ]
}
//存储数据
const list = ref<any>({
    overview: [],  // 督办
    detail: [],   // 督办详情
})

const userList = ref<any[]>([]); // 用户列表
// 表单列配置项
const columns = {
    overview: [
        { prop: 'supName', label: '督办名称', width: 120 },
        {
            prop: 'userId',
            label: '执行人',
            align: 'center',
            width: 90,
            format: (val: any) => {
                return userList.value.find((user) => user.id === val)?.nickname || val;
            },

        },
        {
            prop: 'creator',
            label: '被督办人',
            align: 'center',
            width: 90,
            format: (val: any) => {
                return userList.value.find((user) => user.id === val)?.nickname || val;
            },

        },
        {
            prop: 'status',
            label: '督办状态',
            align: 'center',
            width: 80,
            format: (val: any) => getDictLabel(DICT_TYPE.OA_SUPERVISION_STATUS, val),
            color: (val: any) => getDictColor(DICT_TYPE.OA_SUPERVISION_STATUS, val),
            isTag: true
        }

    ],
    detail: [
        { prop: 'content', label: '催办内容', width: 120 },
        {
            prop: 'replyContent',
            label: '回复状态',
            align: 'center',
            width: 80,
            format: (val: any) => (val ? '已回复'
                : '未回复'),
            color: (val: any) => (val ? 'success'
                : 'warning'),
            isTag: true
        },
        { prop: 'replyContent', label: '回复内容', width: 120 },



    ]

} as any
const activeTab = ref('overview')
const tabs = ref([
    {
        label: '督办',
        value: 'overview',
        api: SupervisionApi.getSupervisionList,
    },
    {
        label: '督办详情',
        value: 'detail',
        api: SupervisionApi.getSupervisionInfoList,
    }
])

// 查询参数
const queryParams = ref<any>({
    pageNo: 1,
    pageSize: 10,

    supName: '',


})
const total = ref(0)
const loading = ref(false)

const searchType = ref<string>('督办名称')
const searchValue = ref<string>('')
const menu = ref<any[]>([
    {
        content: '督办名称',
        prop: 'supName'
    },
])
const handleTabChange = async (value: any) => {
    searchValue.value = ''
    queryParams.value.supName = undefined;
    await nextTick();
    fetchList();

}
function handleSearchChange({ item }: { item: any }) {
    searchType.value = item?.content
}
const handlesearch = () => {
    // 找到选中的搜索字段
    const selectedMenu = menu.value.find(item => item.content === searchType.value);
    if (selectedMenu) {
        // 清空之前的搜索条件
        queryParams.value.supName = undefined;
        // 根据选中的搜索类型设置搜索值
        if (activeTab.value === 'overview') {
            queryParams.value.supName = searchValue.value.trim()
        } else {
            queryParams.value.supName = searchValue.value.trim()
        }
        // queryParams.value[selectedMenu.prop] = value.value.trim();
        // 重新获取数据
        fetchList();
    }
};

// 切换分页
const changePage = (newPage: any) => {
    queryParams.value.pageNo = newPage
    fetchList()
}

// 获取单个 tab 数据
const fetchList = async () => {
    const currentTab = tabs.value.find(t => t.value === activeTab.value);
    if (!currentTab) return;

    loading.value = true;
    try {
        const response = await currentTab.api(queryParams.value);
        list.value[activeTab.value] = response.list
        console.log('list.value', list.value);
        total.value = response.total;
        for (let item of list.value[activeTab.value]) {
            item.status = item.isApproved === false ? 0 : item.status;
        }
        console.log('list.value', list.value);
    } catch (error) {
        console.error(error);
    } finally {
        loading.value = false;
    }
};



/** 点击一整行跳转至详情页面 */
const handleClick = async (item: any) => {

    console.log('item', item);
    console.log('activeTab.value', activeTab.value);

    if (activeTab.value === 'overview') {
        activeTab.value = 'detail'

        const supId = list.value.overview[item.rowIndex]?.id
        const res = await SupervisionApi.getSupervisionInfoList({
            pageNo: 1,
            pageSize: 100,
            supId
        })
        console.log('res', res);

        list.value.detail = res.list
        total.value = res.total
        console.log('columns', columns);

    }

    console.log('item', item);
    console.log('activeTab', activeTab.value);


}
/** 新增或编辑页面 */
const handleAddOrEdit = (id?: any, resubmit = false) => {
    let url = ''
    url = `/pagesPackage/OAsystemAutomation/supervision/create`
    if (id) {
        if (resubmit === true) {
            console.log('resubmit', resubmit);
            url += `?id=${id}&resubmit=1`;
        }
        console.log('传过来的Id', id);
        url += `?id=${id}&resubmit=0`;
    } else {
        url += `?resubmit=0`;
    }

    uni.navigateTo({ url })
}

/** 删除操作 */
const handleDelete = async (id: number) => {
    try {
        await message.confirm({
            msg: '您确定要取消吗？',
            title: '提示',
        })

        const apiMap: Record<string, Function> = {
            overview: SupervisionApi.deleteSupervision,
            detail: SupervisionApi.deleteSupervision,

        }

        const api = apiMap[activeTab.value]
        if (!api) throw new Error('未找到对应 API')

        await api(id)
        toast.success('取消成功')
        await fetchList()
    } catch (error) {
        console.log('用户取消了操作或发生错误:', error)
    }
}
/** 获取页面详情 */
const getDetailById = async (id: any) => {
    try {
        console.log('进来了没');
        console.log('id', id);

        const data = await SupervisionApi.getSupervision(Number(id))
        detailData.value = data
        if (detailData.value.url) {
            detailFileList.value = buildFileList(detailData.value.url)
        }
    } catch (error) {
        console.log('加载数据失败')
    }
}
/**详情 */
const handleDetail = (id: any) => {

    detailPopupVisible.value = true
    /** 获取页面详情 */
    console.log('userList.value', userList.value);

    getDetailById(id)
}
/**催办 */
const handleExpedite = (row: any) => {
    expediteForm.value.supId = row.id
    expediteForm.value.creator = row.creator
    expediteForm.value.title = row.supName

    expeditePopupVisible.value = true
}
/**回复按钮 */
const handleReply = (row: any) => {
    replyForm.value.id = row.id
    replyForm.value.supPersonId = row.supPersonId
    replyForm.value.content = row.content
    replyForm.value.replyContent = row.replyContent
    replyPopupVisible.value = true
}
const getUserList = async () => {
    try {
        const res = await getSimpleUserList();
        userList.value = res;
        console.log('userList.value-----', userList.value);

    } catch (error) {
        console.error('获取用户列表失败:', error);
        return [];
    }
};
// 统一的上传成功处理
const handleUploadSuccess = (item: any, response: any, type?: any) => {
    try {
        console.log('response', response);
        const parsedResponse = JSON.parse(response.file.response)
        const fileUrl = parsedResponse.data // 后端返回的url（字符串）
        // const fileName = response.file.name.split('.').slice(0, -1).join('.')
        const fileName = response.file.name
        // 更新目标字段
        if (type === 'reply') {
            replyForm.value.replyAttachment = fileUrl

        } else {
            expediteForm.value.url = fileUrl

        }
        console.log('fileList.value', fileList.value);
        console.log('filreplyFileListeList.value', replyFileList.value);

        toast.success('文件上传成功')
    } catch (error) {
        console.error('文件上传结果解析失败', error)
        toast.error('文件解析失败，请检查格式')
    }
}
/** 提交催办 */
const submitExpedite = async () => {
    try {
        const { valid, errors } = await auditForm.value.validate();
        if (!valid) {
            console.log('表单校验未通过:', errors);
            return; // ✅ 校验失败，终止后续代码
        }
        if (!expediteForm.value.content.trim()) {
            toast.error('请填写催办内容')
            return
        }
        console.log('expediteForm.value', expediteForm.value);

        const logId = await SupervisionApi.sendSupervisionApply(expediteForm.value)
        if (logId) {
            expediting({
                userId: expediteForm.value.creator,
                processName: '青运-办公系统自动化-督办管理',
                templateCode: 'supervisio-seed',
                info:{
                    title: expediteForm.value.title,
                    content: expediteForm.value.content,
                }

            })
        }
        console.log(logId, 'AAAAAAAAAAA')

        if (logId) {
            toast.success('催办成功')
        }


        expeditePopupVisible.value = false
    } catch (err) {
        console.error('催办失败:', err)
    }
}
/** 提交回复 */
const submitReply = async () => {
    try {
        const { valid, errors } = await replyFormRef.value.validate();
        if (!valid) {
            console.log('表单校验未通过:', errors);
            return; // ✅ 校验失败，终止后续代码
        }

        console.log('replyForm.value', replyForm.value);

        const logId = await SupervisionApi.replySupervisionInfo(replyForm.value)
        console.log('logId', logId);

        if (logId) {
            expediting({
                userId: replyForm.value.supPersonId,
                processName: '青运-办公系统自动化-督办管理',
                templateCode: 'supervision-reply',
                info:{
                    title: replyForm.value.content,
                    content: replyForm.value.replyContent,
                }

            })
        }
        console.log(logId, 'AAAAAAAAAAA')

        if (logId) {
            toast.success('回复成功')
        }


        replyPopupVisible.value = false
    } catch (err) {
        console.error('回复失败:', err)
    }
}
onShow(() => {
    fetchList()
    getUserList()

})
</script>

<style scoped lang="scss">
.file-link {
    color: #007AFF;
    text-decoration: underline;
    cursor: pointer;
}
</style>